package com.geo.auth.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.geo.auth.entity.Permission;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 权限Mapper接口
 */
@Mapper
public interface PermissionMapper extends BaseMapper<Permission> {
    
    /**
     * 根据用户ID查询用户权限
     */
    @Select("SELECT DISTINCT p.* FROM permissions p " +
            "INNER JOIN role_permissions rp ON p.id = rp.permission_id " +
            "INNER JOIN user_roles ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId} AND p.deleted = 0 AND rp.deleted = 0 AND ur.deleted = 0")
    List<Permission> findByUserId(@Param("userId") String userId);
    
    /**
     * 根据角色ID查询角色权限
     */
    @Select("SELECT p.* FROM permissions p " +
            "INNER JOIN role_permissions rp ON p.id = rp.permission_id " +
            "WHERE rp.role_id = #{roleId} AND p.deleted = 0 AND rp.deleted = 0")
    List<Permission> findByRoleId(@Param("roleId") String roleId);
    
    /**
     * 根据权限代码查询权限
     */
    @Select("SELECT * FROM permissions WHERE permission_code = #{permissionCode} AND deleted = 0")
    Permission findByPermissionCode(@Param("permissionCode") String permissionCode);
    
    /**
     * 查询所有启用的权限
     */
    @Select("SELECT * FROM permissions WHERE status = 'ACTIVE' AND deleted = 0 ORDER BY sort_order ASC")
    List<Permission> findActivePermissions();
    
    /**
     * 根据权限类型查询权限
     */
    @Select("SELECT * FROM permissions WHERE permission_type = #{type} AND deleted = 0")
    List<Permission> findByType(@Param("type") String type);
    
    /**
     * 根据父权限ID查询子权限
     */
    @Select("SELECT * FROM permissions WHERE parent_id = #{parentId} AND deleted = 0 ORDER BY sort_order ASC")
    List<Permission> findByParentId(@Param("parentId") String parentId);
    
    /**
     * 检查权限代码是否存在
     */
    @Select("SELECT COUNT(*) FROM permissions WHERE permission_code = #{permissionCode} AND deleted = 0")
    int countByPermissionCode(@Param("permissionCode") String permissionCode);
    
    /**
     * 兼容性方法 - 根据用户ID查询权限
     */
    default List<Permission> selectPermissionsByUserId(String userId) {
        return findByUserId(userId);
    }
}